package com.alinesno.cloud.common.web.login.dialect.processor;

import static org.thymeleaf.util.StringUtils.trim;
import static org.thymeleaf.util.Validate.notEmpty;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.spring5.context.SpringContextUtils;
import org.thymeleaf.templatemode.TemplateMode;

import com.alinesno.cloud.base.boot.entity.ManagerAccountEntity;
import com.alinesno.cloud.common.web.login.auth.UnauthorizedOperationException;
import com.alinesno.cloud.common.web.login.session.CurrentAccountSession;

public class HasPermissionAttrProcessor extends AbstractAttributeTagProcessor {

	private static final Logger log = LoggerFactory.getLogger(HasPermissionAttrProcessor.class) ; 
	
    private static final String ATTRIBUTE_NAME = "hasPermission";
    private static final int PRECEDENCE = 300;

    public HasPermissionAttrProcessor(String dialectPrefix) {
        super(TemplateMode.HTML,dialectPrefix, null,false, ATTRIBUTE_NAME, true, PRECEDENCE, true); 
    }

    @Override
    protected void doProcess(ITemplateContext iTemplateContext,
                             IProcessableElementTag iProcessableElementTag,
                             AttributeName attributeName,
                             String attributeValue,
                             IElementTagStructureHandler iElementTagStructureHandler) {

    	log.debug("attribute name:{} ,  value:{}" , attributeName.getAttributeName() , attributeValue);
        notEmpty(attributeValue , "value of '" + ATTRIBUTE_NAME + "' must not be empty");
    	
    	ApplicationContext ctx = SpringContextUtils.getApplicationContext(iTemplateContext);
    	CurrentAccountSession currentAccountSession = ctx.getBean(CurrentAccountSession.class) ; 
    	
    	ManagerAccountEntity account = currentAccountSession.get(); 
    	Set<String> permission =account.getPermission() ;
    	
    	if(permission == null	) {
    		throw new UnauthorizedOperationException("没有操作权限.") ; 
    	}
    	
    	if(permission.contains(trim(attributeValue))) {  // 包含权限 
            iElementTagStructureHandler.removeAttribute(attributeName);
    	}else {
    		iElementTagStructureHandler.removeElement();
    	}
    	
    }
}